package serverComuncation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import communicationMessages.Message;




//import com.sun.org.apache.bcel.internal.generic.InstructionConstants.Clinit;
/**
 * this class is the connection handler it creats the connection queue and
 * activates the connection threads.
 * @author orrlev
 *
 */
class ConnectionHandler implements Runnable
{


	//private StompQueue queue;
	private BufferedReader in;
	private PrintWriter out;


	private Socket clientSocket;
	/**
	 * consturcor
	 * @param acceptedSocket socket
	 * @param messagesHendler_ mailBox
	 * @param contactList_ subscribes
	 */
	public ConnectionHandler(Socket acceptedSocket)
	{
		this.in = null;
		this.out = null;
		this.clientSocket = acceptedSocket;
		System.out.println("Accepted connection from client!");
		System.out.println("The client is from: " +
		acceptedSocket.getInetAddress() + ":" + acceptedSocket.getPort());
	 }
	/**
	 *
	 */
	public void run()
	{
		try
		{
			this.initialize();
		}
		catch (IOException e)
		{
			System.out.println("Error in initializing I/O");
		}
		while (true){
			
			try {
				writeMsg(Message.addFinshToAns("hello to my server\n"));
				String msg = readMessage();
				String ansMsg = handleMsg(msg);
				writeMsg(Message.addFinshToAns(ansMsg));
				writeMsg(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				close();
				break;
				
			}
			
		}
	}



	private void writeMsg(String ansMsg) {
		System.out.println(ansMsg);
		out.write(ansMsg);
	}
	
	private String handleMsg(String msg) {
		Message m = Message.parseMsg(msg);
		return m.getAnswer();
	}
	private String readMessage() throws IOException {
		String ans ="";
		System.out.println("start reading");
		String line = in.readLine();
		while (!line.equals("\0")){
			ans+=line+"\n";
			line =in.readLine();
		}
		System.out.println("finshed reading");
		return ans;
	}
	// Starts listening
	public void initialize() throws IOException
	{
		// Initialize I/O
		this.in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
		this.out = new PrintWriter(this.clientSocket.getOutputStream(), true);
		System.out.println("I/O initialized");
	}
	// Closes the connection
	public void close()
	{
		try
		{
			if (this.in != null)
			{
				this.in.close();
			}
			if (this.out != null)
			{
				this.out.close();
			}
			this.clientSocket.close();
		}
		catch (IOException e)
		{
			System.out.println("Exception in closing I/O");
	    }
	}
}
